// 存储键定义
const CART_KEY = 'mall_cart';
const FAVORITES_KEY = 'mall_favorites';
const ADDRESSES_KEY = 'mall_addresses';
const ORDERS_KEY = 'mall_orders';
const BROWSE_HISTORY_KEY = 'mall_browse_history';
const USER_KEY = 'mall_user';
const PRODUCTS_KEY = 'mall_products';
const ADMIN_ORDERS_KEY = 'mall_admin_orders';
const USERS_KEY = 'mall_users';
const ADMIN_USERS_KEY = 'mall_admin_users';
const CATEGORIES_KEY = 'mall_categories';
const REFUNDS_KEY = 'mall_refunds';
const LOGS_KEY = 'mall_logs';
const ADMIN_USER_KEY = 'mall_admin_user';

// 数据重置函数（开发时使用）
export const resetAllData = () => {
  localStorage.removeItem(CART_KEY);
  localStorage.removeItem(FAVORITES_KEY);
  localStorage.removeItem(ADDRESSES_KEY);
  localStorage.removeItem(ORDERS_KEY);
  localStorage.removeItem(BROWSE_HISTORY_KEY);
  localStorage.removeItem(USER_KEY);
  localStorage.removeItem(PRODUCTS_KEY);
  localStorage.removeItem(ADMIN_ORDERS_KEY);
  localStorage.removeItem(USERS_KEY);
  localStorage.removeItem(ADMIN_USERS_KEY);
  localStorage.removeItem(CATEGORIES_KEY);
  localStorage.removeItem(REFUNDS_KEY);
  localStorage.removeItem(LOGS_KEY);
  localStorage.removeItem(ADMIN_USER_KEY);
  localStorage.removeItem('mall_token');
  localStorage.removeItem('mall_points_history');
  console.log('所有本地数据已重置，请刷新页面重新初始化数据');
};

// 商品管理
export const getProducts = () => {
  const products = localStorage.getItem(PRODUCTS_KEY);
  console.log('获取商品列表:', products);
  return products ? JSON.parse(products) : [];
};

export const setProducts = (products) => {
  localStorage.setItem(PRODUCTS_KEY, JSON.stringify(products));
};

export const addProduct = (product) => {
  const products = getProducts();
  const newProduct = {
    ...product,
    id: Date.now(),
    createTime: Date.now(),
    sales: 0,
    views: 0,
    status: 'active'
  };
  products.push(newProduct);
  setProducts(products);
  return newProduct;
};

export const updateProduct = (productId, productData) => {
  const products = getProducts();
  const index = products.findIndex(p => p.id === productId);
  if (index !== -1) {
    products[index] = { ...products[index], ...productData };
    setProducts(products);
    return products[index];
  }
  return null;
};

export const updateProductSales = (productId, quantity = 1) => {
  const products = getProducts();
  const product = products.find(p => p.id === productId);
  if (product) {
    product.sales = (product.sales || 0) + quantity;
    setProducts(products);
    return product;
  }
  return null;
};

// 新增：更新商品库存
export const updateProductStock = (productId, quantity = 1) => {
  const products = getProducts();
  const product = products.find(p => p.id === productId);
  if (product && product.stock >= quantity) {
    product.stock = product.stock - quantity;
    setProducts(products);
    return product;
  }
  return null;
};

export const deleteProduct = (productId) => {
  const products = getProducts();
  const newProducts = products.filter(p => p.id !== productId);
  setProducts(newProducts);
  return newProducts;
};

// 分类管理
export const getCategories = () => {
  const categories = localStorage.getItem(CATEGORIES_KEY);
  return categories ? JSON.parse(categories) : [];
};

export const setCategories = (categories) => {
  localStorage.setItem(CATEGORIES_KEY, JSON.stringify(categories));
};

export const addCategory = (category) => {
  const categories = getCategories();
  const newCategory = {
    ...category,
    id: Date.now(),
    createTime: Date.now(),
    productCount: 0
  };
  categories.push(newCategory);
  setCategories(categories);
  return newCategory;
};

export const updateCategory = (categoryId, categoryData) => {
  const categories = getCategories();
  const index = categories.findIndex(c => c.id === categoryId);
  if (index !== -1) {
    categories[index] = { ...categories[index], ...categoryData };
    setCategories(categories);
    return categories[index];
  }
  return null;
};

export const deleteCategory = (categoryId) => {
  const categories = getCategories();
  const newCategories = categories.filter(c => c.id !== categoryId);
  setCategories(newCategories);
  return newCategories;
};

// 管理员用户管理
export const getAdminUsers = () => {
  const adminUsers = localStorage.getItem(ADMIN_USERS_KEY);
  return adminUsers ? JSON.parse(adminUsers) : [];
};

export const setAdminUsers = (adminUsers) => {
  localStorage.setItem(ADMIN_USERS_KEY, JSON.stringify(adminUsers));
};

export const addAdminUser = (user) => {
  const adminUsers = getAdminUsers();
  const newUser = {
    ...user,
    id: Date.now(),
    createTime: Date.now(),
    status: user.status || 'active'
  };
  adminUsers.push(newUser);
  setAdminUsers(adminUsers);
  return newUser;
};

export const updateAdminUser = (userId, userData) => {
  const adminUsers = getAdminUsers();
  const index = adminUsers.findIndex(u => u.id === userId);
  if (index !== -1) {
    adminUsers[index] = { ...adminUsers[index], ...userData };
    setAdminUsers(adminUsers);
    return adminUsers[index];
  }
  return null;
};

export const deleteAdminUser = (userId) => {
  const adminUsers = getAdminUsers();
  const newUsers = adminUsers.filter(u => u.id !== userId);
  setAdminUsers(newUsers);
  return newUsers;
};

// 售后管理
export const getRefunds = () => {
  const refunds = localStorage.getItem(REFUNDS_KEY);
  return refunds ? JSON.parse(refunds) : [];
};

export const setRefunds = (refunds) => {
  localStorage.setItem(REFUNDS_KEY, JSON.stringify(refunds));
};

export const addRefund = (refund) => {
  const refunds = getRefunds();
  const newRefund = {
    ...refund,
    id: Date.now(),
    refundNo: 'REF' + Date.now(),
    createTime: Date.now(),
    status: 'pending'
  };
  refunds.unshift(newRefund);
  setRefunds(refunds);
  return newRefund;
};

export const updateRefund = (refundId, refundData) => {
  const refunds = getRefunds();
  const index = refunds.findIndex(r => r.id === refundId);
  if (index !== -1) {
    refunds[index] = { ...refunds[index], ...refundData };
    setRefunds(refunds);
    return refunds[index];
  }
  return null;
};

// 日志管理
export const getLogs = () => {
  const logs = localStorage.getItem(LOGS_KEY);
  return logs ? JSON.parse(logs) : [];
};

export const setLogs = (logs) => {
  // 只保留最近1000条日志
  const recentLogs = logs.slice(0, 1000);
  localStorage.setItem(LOGS_KEY, JSON.stringify(recentLogs));
};

export const addLog = (logData) => {
  const logs = getLogs();
  const newLog = {
    id: Date.now(),
    ...logData,
    createTime: Date.now(),
    ipAddress: getIPAddress(),
    device: getDeviceInfo(),
    browser: getBrowserInfo(),
    location: '中国',
    duration: Math.floor(Math.random() * 100) + 50,
    result: logData.result || 'success'
  };
  
  logs.unshift(newLog);
  setLogs(logs);
  return newLog;
};

// 辅助函数
const getIPAddress = () => {
  const ips = [
    '192.168.1.100',
    '192.168.1.101',
    '192.168.1.102',
    '10.0.0.50',
    '10.0.0.51'
  ];
  return ips[Math.floor(Math.random() * ips.length)];
};

const getDeviceInfo = () => {
  const userAgent = navigator.userAgent;
  if (/mobile/i.test(userAgent)) {
    return 'Mobile Device';
  } else if (/windows/i.test(userAgent)) {
    return 'Windows PC';
  } else if (/mac/i.test(userAgent)) {
    return 'Mac';
  }
  return 'Desktop';
};

const getBrowserInfo = () => {
  const userAgent = navigator.userAgent;
  if (/chrome/i.test(userAgent) && !/edge/i.test(userAgent)) {
    return 'Chrome';
  } else if (/safari/i.test(userAgent) && !/chrome/i.test(userAgent)) {
    return 'Safari';
  } else if (/firefox/i.test(userAgent)) {
    return 'Firefox';
  } else if (/edge/i.test(userAgent)) {
    return 'Edge';
  }
  return 'Unknown Browser';
};

// 管理员订单管理
export const getAdminOrders = () => {
  const orders = localStorage.getItem(ADMIN_ORDERS_KEY);
  return orders ? JSON.parse(orders) : [];
};

export const setAdminOrders = (orders) => {
  localStorage.setItem(ADMIN_ORDERS_KEY, JSON.stringify(orders));
};

export const addAdminOrder = (order) => {
  const orders = getAdminOrders();
  const newOrder = {
    ...order,
    id: Date.now(),
    orderNo: 'ORD' + Date.now(),
    createTime: Date.now(),
    status: 'pending'
  };
  orders.unshift(newOrder);
  setAdminOrders(orders);
  return newOrder;
};

export const updateAdminOrderStatus = (orderId, status) => {
  const orders = getAdminOrders();
  const order = orders.find(o => o.id === orderId);
  if (order) {
    order.status = status;
    const now = Date.now();
    
    if (status === 'paid') {
      order.payTime = now;
      // 支付后24小时内自动发货（模拟）
      setTimeout(() => {
        updateAdminOrderStatus(orderId, 'shipped');
      }, 24 * 60 * 60 * 1000); // 24小时
    } else if (status === 'shipped') {
      order.shipTime = now;
      // 发货后2-3天自动变为已送达（模拟）
      const deliveryTime = 2 + Math.random(); // 2-3天
      setTimeout(() => {
        updateAdminOrderStatus(orderId, 'delivered');
      }, deliveryTime * 24 * 60 * 60 * 1000);
    } else if (status === 'delivered') {
      order.deliverTime = now;
    }
    
    setAdminOrders(orders);
    
    // 同时更新前台用户订单数据
    const userOrders = getOrders();
    const userOrder = userOrders.find(o => o.id === orderId);
    if (userOrder) {
      userOrder.status = status;
      if (status === 'paid') {
        userOrder.payTime = now;
      } else if (status === 'shipped') {
        userOrder.shipTime = now;
        userOrder.logistics = order.logistics;
        userOrder.trackingNumber = order.trackingNumber;
      } else if (status === 'delivered') {
        userOrder.deliverTime = now;
      }
      setOrders(userOrders);
    }
  }
  return orders;
};

// 新增：更新完整的管理员订单信息（不仅仅是状态）
export const updateAdminOrder = (orderId, orderData) => {
  const orders = getAdminOrders();
  const index = orders.findIndex(o => o.id === parseInt(orderId));
  if (index !== -1) {
    orders[index] = { ...orders[index], ...orderData };
    setAdminOrders(orders);
    
    // 同时更新前台用户订单数据
    const userOrders = getOrders();
    const userIndex = userOrders.findIndex(o => o.id === parseInt(orderId));
    if (userIndex !== -1) {
      userOrders[userIndex] = { ...userOrders[userIndex], ...orderData };
      setOrders(userOrders);
    }
    
    return orders[index];
  }
  return null;
};

// 新增：更新用户订单信息（前台订单也需要同步更新）
export const updateOrder = (orderId, orderData) => {
  const orders = getOrders();
  const index = orders.findIndex(o => o.id === parseInt(orderId));
  if (index !== -1) {
    orders[index] = { ...orders[index], ...orderData };
    setOrders(orders);
    
    // 同时更新管理员订单
    updateAdminOrder(orderId, orderData);
    return orders[index];
  }
  return null;
};

// 购物车操作
export const getCart = () => {
  const cart = localStorage.getItem(CART_KEY);
  return cart ? JSON.parse(cart) : [];
};

export const setCart = (cart) => {
  localStorage.setItem(CART_KEY, JSON.stringify(cart));
};

export const addToCart = (product) => {
  const cart = getCart();
  const existingItem = cart.find(item => 
    item.id === product.id && 
    JSON.stringify(item.selectedSpecs) === JSON.stringify(product.selectedSpecs)
  );
  
  if (existingItem) {
    existingItem.quantity += product.quantity;
  } else {
    cart.push({
      ...product,
      cartId: Date.now() + Math.random()
    });
  }
  
  setCart(cart);
  return cart;
};

export const removeFromCart = (cartId) => {
  const cart = getCart();
  const newCart = cart.filter(item => item.cartId !== cartId);
  setCart(newCart);
  return newCart;
};

export const updateCartQuantity = (cartId, quantity) => {
  const cart = getCart();
  const item = cart.find(item => item.cartId === cartId);
  if (item) {
    item.quantity = quantity;
    setCart(cart);
  }
  return cart;
};

// 收藏操作
export const getFavorites = () => {
  const favorites = localStorage.getItem(FAVORITES_KEY);
  return favorites ? JSON.parse(favorites) : [];
};

export const addToFavorites = (product) => {
  const favorites = getFavorites();
  const exists = favorites.find(item => item.id === product.id);
  if (!exists) {
    favorites.push({
      ...product,
      favoriteTime: Date.now()
    });
    localStorage.setItem(FAVORITES_KEY, JSON.stringify(favorites));
  }
  return favorites;
};

export const removeFromFavorites = (productId) => {
  const favorites = getFavorites();
  const newFavorites = favorites.filter(item => item.id !== productId);
  localStorage.setItem(FAVORITES_KEY, JSON.stringify(newFavorites));
  return newFavorites;
};

export const isFavorite = (productId) => {
  const favorites = getFavorites();
  return favorites.some(item => item.id === productId);
};

// 地址管理
export const getAddresses = () => {
  const addresses = localStorage.getItem(ADDRESSES_KEY);
  return addresses ? JSON.parse(addresses) : [];
};

export const setAddresses = (addresses) => {
  localStorage.setItem(ADDRESSES_KEY, JSON.stringify(addresses));
};

export const addAddress = (address) => {
  const addresses = getAddresses();
  const newAddress = {
    ...address,
    id: Date.now(),
    createTime: Date.now()
  };
  addresses.push(newAddress);
  setAddresses(addresses);
  return newAddress;
};

export const updateAddress = (addressId, address) => {
  const addresses = getAddresses();
  const index = addresses.findIndex(item => item.id === addressId);
  if (index !== -1) {
    addresses[index] = { ...addresses[index], ...address };
    setAddresses(addresses);
  }
  return addresses;
};

export const deleteAddress = (addressId) => {
  const addresses = getAddresses();
  const newAddresses = addresses.filter(item => item.id !== addressId);
  setAddresses(newAddresses);
  return newAddresses;
};

// 订单管理（前台用户订单）
export const getOrders = () => {
  const orders = localStorage.getItem(ORDERS_KEY);
  console.log('获取用户订单:', orders);
  return orders ? JSON.parse(orders) : [];
};

export const setOrders = (orders) => {
  localStorage.setItem(ORDERS_KEY, JSON.stringify(orders));
};

export const addOrder = (order) => {
  const userInfo = getUserInfo();
  
  const newOrder = {
    ...order,
    id: Date.now(),
    orderNo: 'ORD' + Date.now(),
    createTime: Date.now(),
    status: 'pending' // pending, paid, shipped, delivered, cancelled
  };
  
  // 添加到用户订单
  const orders = getOrders();
  orders.unshift(newOrder);
  setOrders(orders);
  
  // 同时添加到管理员订单列表
  const adminOrders = getAdminOrders();
  const adminOrder = {
    ...newOrder,
    userId: userInfo?.id || 1,
    userName: userInfo?.nickname || userInfo?.username || '用户',
    userPhone: order.address?.phone || userInfo?.phone || '',
    address: typeof order.address === 'string' ? order.address : 
      `${order.address?.province || ''} ${order.address?.city || ''} ${order.address?.district || ''} ${order.address?.detail || ''}`,
    items: order.products || []
  };
  adminOrders.unshift(adminOrder);
  setAdminOrders(adminOrders);
  
  return newOrder;
};

export const updateOrderStatus = (orderId, status) => {
  const orders = getOrders();
  const order = orders.find(item => item.id === orderId);
  
  if (order) {
    order.status = status;
    const now = Date.now();
    
    if (status === 'paid') {
      order.payTime = now;
      // 支付后模拟24小时内发货
      setTimeout(() => {
        updateOrderStatus(orderId, 'shipped');
      }, 24 * 60 * 60 * 1000);
    } else if (status === 'shipped') {
      order.shipTime = now;
      // 发货后模拟2-3天送达
      const deliveryDays = 2 + Math.random(); // 2-3天随机
      setTimeout(() => {
        updateOrderStatus(orderId, 'delivered');
      }, deliveryDays * 24 * 60 * 60 * 1000);
    } else if (status === 'delivered') {
      order.deliverTime = now;
      // 订单完成时奖励积分
      import('./points').then(module => {
        module.giveOrderPoints(order.totalAmount);
      });
      
      // 订单完成时更新商品销量和库存
      if (order.products && order.products.length > 0) {
        order.products.forEach(product => {
          updateProductSales(product.id, product.quantity);
          updateProductStock(product.id, product.quantity);
        });
      }
    }
    
    setOrders(orders);
  }
  
  // 同时更新管理员订单状态
  updateAdminOrderStatus(orderId, status);
  
  return orders;
};

// 获取用户的特定订单
export const getUserOrder = (orderId) => {
  const orders = getOrders();
  return orders.find(order => order.id === parseInt(orderId));
};

// 浏览历史
export const getBrowseHistory = () => {
  const history = localStorage.getItem(BROWSE_HISTORY_KEY);
  return history ? JSON.parse(history) : [];
};

export const addToBrowseHistory = (product) => {
  const history = getBrowseHistory();
  // 移除已存在的相同商品
  const filteredHistory = history.filter(item => item.id !== product.id);
  // 添加到开头
  filteredHistory.unshift({
    ...product,
    browseTime: Date.now()
  });
  // 只保留最近50条记录
  const newHistory = filteredHistory.slice(0, 50);
  localStorage.setItem(BROWSE_HISTORY_KEY, JSON.stringify(newHistory));
  return newHistory;
};

// 获取用户信息
export const getUserInfo = () => {
  const userInfo = localStorage.getItem(USER_KEY);
  return userInfo ? JSON.parse(userInfo) : null;
};

// 普通用户管理
export const getUsers = () => {
  const users = localStorage.getItem(USERS_KEY);
  return users ? JSON.parse(users) : [];
};

export const setUsers = (users) => {
  localStorage.setItem(USERS_KEY, JSON.stringify(users));
};

export const addUser = (user) => {
  const users = getUsers();
  
  // 检查用户名是否已存在
  const isExist = users.some(u => u.username === user.username);
  if (isExist) {
    return { success: false, message: '用户名已存在' };
  }
  
  const newUser = {
    ...user,
    id: user.id || Date.now(),
    createTime: user.createTime || Date.now(),
    status: user.status || 'active',
    level: user.level || '普通会员',
    points: user.points || 0
  };
  
  users.push(newUser);
  setUsers(users);
  return { success: true, data: newUser };
};

export const updateUser = (userId, userData) => {
  const users = getUsers();
  const index = users.findIndex(u => u.id === userId);
  if (index !== -1) {
    users[index] = { ...users[index], ...userData };
    setUsers(users);
    return users[index];
  }
  return null;
};

export const deleteUser = (userId) => {
  const users = getUsers();
  const newUsers = users.filter(u => u.id !== userId);
  setUsers(newUsers);
  return newUsers;
};